package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private IUserService userService;

    private final StringRedisTemplate stringRedisTemplate;

    public FollowServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 判断用户是否已关注
     * @param id
     * @return
     */
    @Override
    public Result isFollow(Long id) {
        Long userId = UserHolder.getUser().getId();
        LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follow::getUserId, userId).eq(Follow::getFollowUserId,id);
        int count = this.count(queryWrapper);
        return Result.ok(count > 0);
    }

    /**
     * 关注或取消关注用户
     * @param followId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followId, Boolean isFollow) {
        try {
            Long id = UserHolder.getUser().getId();
            String key = "follows:" + id;

            if (isFollow) {
                //关注用户
                Follow follow = new Follow();
                follow.setUserId(id);
                follow.setFollowUserId(followId);
                boolean isSuccess = this.save(follow);
                if (isSuccess){
                    //加入关注用户到缓存中
                    stringRedisTemplate.opsForSet().add(key, String.valueOf(followId));
                }
            }else {
                //取消关注
                LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Follow::getFollowUserId,followId).eq(Follow::getUserId,id);
                boolean isSuccess = this.remove(queryWrapper);
                if (isSuccess){
                    //将取消关注的用户移出缓存
                    stringRedisTemplate.opsForSet().remove(key, String.valueOf(followId));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.fail(e.getMessage());
        }

        return Result.ok();
    }

    /**
     * 获取共同关注的用户
     * @param followId
     * @return
     */
    @Override
    public Result followCommons(Long followId) {
        //1.获取当前登陆的用户Id
        Long userId = UserHolder.getUser().getId();

        //2.根据传入的用户Id，查询与当前用户的关注列表的交集
        String key = "follows:" + userId;
        String otherKey = "follows:" + followId;
        Set<String> commonFollowUserList = stringRedisTemplate.opsForSet().intersect(key, otherKey);
        if (commonFollowUserList==null || commonFollowUserList.isEmpty()) {
            //无交集
            return Result.ok(Collections.emptyList());
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(User::getId, commonFollowUserList);

        List<UserDTO> userDTOList = userService.list(queryWrapper)
                .stream()
                .map(item -> {
                    UserDTO userDTO = new UserDTO();
                    BeanUtils.copyProperties(item, userDTO);
                    return userDTO;
                })
                .collect(Collectors.toList());

        return Result.ok(userDTOList);
    }
}
